package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"house/api/request"
	"house/api/resp"
	"house/consts"
	"house/internal/dao"
	"house/internal/model"
	"time"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)
	if user.Id > 0 {
		resp.Error(c, 100000, "用户已注册，请前去登录", false)
		return
	}
	if req.Password != req.AckPassword {
		resp.Error(c, 100000, "两次密码不一致", false)
		return
	}
	result := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
		TypeUser: req.TypeUser,
	})
	if !result {
		resp.Error(c, 100000, "注册失败", false)
		return
	}
	resp.Success(c, "注册成功", true)
}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile, Password: req.Password}, &user)
	if user.Id == 0 {
		resp.Error(c, 100000, "账号或密码错误", false)
		return
	}

	token, err := gojwt.NewJWT(consts.Jwt_KEY).CreateToken(gojwt.CustomClaims{
		ID:          user.Id,
		AuthorityId: user.TypeUser,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() * 3600 * 24 * 3,
		},
	})
	if err != nil {
		resp.Error(c, 100000, "生成token失败", false)
		return
	}

	resp.Success(c, "登录成功", token)
}

func RefreshToken(c *gin.Context) {
	userId := c.GetUint("userId")
	token, err := gojwt.NewJWT(consts.Jwt_KEY).CreateToken(gojwt.CustomClaims{
		ID: userId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() * 3600 * 24 * 3,
		},
	})
	if err != nil {
		resp.Error(c, 100000, "生成token失败", false)
		return
	}

	resp.Success(c, "token刷新成功", token)
}
